#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include "yaffs_ioctl.h"

int main(int argc, char *argv[]) {
    char level[ARG_LENGTH];
    char pass[ARG_LENGTH];
    int fd = -1;
    int return_value;
    struct termios oldt, newt;

    if ((fd = open("/dev/defy", O_RDWR)) < 0) {
	printf("DEFY not running\n");
	return -1;
    }
  
    if(argc > 2) {
	strcpy(level, argv[1]);
	if(ioctl(fd, SET_LEVEL_ID, level) < 0) {
	    perror("Level ID");
	    return -1;
	}

	strcpy(pass, argv[2]);
	if(ioctl(fd, SET_PASSWORD, pass) < 0) {
	    memset(pass, 0, ARG_LENGTH);
	    perror("Password");
	    return -1;
	}
    } else {
	// Set environment to not echo credential entry
	tcgetattr(STDIN_FILENO, &oldt);
	newt = oldt;
	newt.c_lflag &= ~ECHO;
	tcsetattr(STDIN_FILENO, TCSANOW, &newt);

	printf("Enter credentials:\n");
	printf("Level ID: ");
	scanf("%s", level);
	printf("\n");
	if(ioctl(fd, SET_LEVEL_ID, level) < 0) {
	    memset(level, 0, ARG_LENGTH);
	    // Return to original environment
	    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
	    perror("Level ID");
	    return -1;
	}
	
	printf("Password: ");
	scanf("%s", pass);
	printf("\n");
	if(ioctl(fd, SET_PASSWORD, pass) < 0) {
	    memset(pass, 0, ARG_LENGTH);
	    // Return to original environment
	    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
	    perror("Password");
	    return -1;
	}
	// Return to original environment
	tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    }

    memset(level, 0, ARG_LENGTH);
    memset(pass, 0, ARG_LENGTH);

    if(ioctl(fd, OPEN_LEVEL) < 0) {
	perror("Open");
	return -1;
    } else {
	printf("Successfully opened level\n");
    }
    return 0;
}
